﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dac.Entities;
using Dapper;

namespace Dac.DAL.Repositories
{
    public class ProductRepository : BaseRepository<Product>
    {
        public IEnumerable<Product> FindAll()
        {
            IEnumerable<Product> result = Connection.Query<Product>(
                @"  select p.ProductId, p.ProductNameRu, p.ProductNameEn, p.PreviewImage
                    from [Product] (nolock) as p");
            return result;
        }

        public Product Find(int productId)
        {
            Product result = Connection.Query<Product>(
                @"  select p.ProductId, p.ProductNameRu, p.ProductNameEn, 
                        p.ProductDescRu, p.ProductDescEn, 
                        p.PreviewImage, p.MainImage,
                        p.Price, p.IsShow, p.OutStock
                    from [Product] (nolock) as p
                    where p.ProductId = @ProductId", new { ProductId = productId }).SingleOrDefault();
            return result;
        }

        public void Insert(Product item)
        {
            int result = Connection.Query<int>(
                @"insert into Product
                (ProductNameRu, ProductNameEn, ProductDescRu, ProductDescEn, PreviewImage, MainImage, Price, IsShow, OutStock) 
                values (@ProductNameRu, @ProductNameEn, @ProductDescRu, @ProductDescEn, @PreviewImage, @MainImage, @Price, @IsShow, @OutStock); 
                select CAST(SCOPE_IDENTITY() AS INT);", item).Single();
            item.ProductId = result;
        }

        public void Update(Product item)
        {
            Connection.Execute(
                @"update Product
                set ProductNameRu = @ProductNameRu, ProductNameEn = @ProductNameEn, ProductDescRu = @ProductDescRu, ProductDescEn = @ProductDescEn, PreviewImage = isnull(@PreviewImage, PreviewImage), MainImage = isnull(@MainImage, MainImage), Price = @Price, IsShow = @IsShow, OutStock = @OutStock
                where (ProductId = @ProductId)", item);
        }

        public void Delete(int productId)
        {
            Connection.Execute(
                @"delete 
                    from Product
                    where (ProductId = @ProductId)", new { ProductId = productId });
        }
    }
}
